package com.b2.controller.wx;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.alibaba.fastjson.JSONObject;
import com.b2.properties.WeChatProperties;
import com.b2.service.PushService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RequestMapping
@RestController
@Slf4j
public class PushController {

    @Autowired
    private PushService pushService;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private WxMaService wxMaService;

    /**
     * 消息校验，确定是微信发送的消息
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     * @throws Exception
     */
    @GetMapping("/get")
    @ApiOperation( "消息校验，确定是微信发送的消息")
    //-------------微信小程序消息验证,signature:072146db664ac6e89cf22ceb5ee35c0dc7536a66,timestamp:1720665348,nonce:190254112,echostr:7375403449705256878
    public Long doGet(String signature, String timestamp, String nonce, Long echostr) {
        log.info("-------------微信小程序消息验证,signature:{},timestamp:{},nonce:{},echostr:{}", signature, timestamp, nonce, echostr);
        // 消息合法
        if (wxMaService.checkSignature(timestamp, nonce, signature)) {
            log.info("-------------微信小程序消息验证通过,echostr:{}", echostr);
            return echostr;
        }
        // 消息签名不正确，说明不是公众平台发过来的消息
        return null;
    }


    /**
     * 发送订阅消息
     * @param request
     * @return
     */
    @PostMapping( "sendMsg")
    @ResponseBody
    @ApiOperation( "发送订阅消息")
    public String sendMsg(HttpServletRequest request){
        //String token = request.getParameter("token");
        //请求 微信接口 获取 accessToken
        String accessToken = pushService.refreshAccessToken(weChatProperties.getAppid(),weChatProperties.getSecret());
        String openid = "oIzyv4l_pmGtI4FrLN4XNtA0GPXE";
        String templateId = weChatProperties.getTemplateId();
        String page = "http://picture.mark.syssts.com:9090/classVideo";
        // 构建订阅消息内容的JSON对象
        // 构建订阅消息内容的JSON对象
        JSONObject messageData = new JSONObject();
        messageData.put("thing1", pushService.createDataItem("提醒内容", "您有新的提醒"));
        messageData.put("thing2", pushService.createDataItem("作业名称", "Java作业"));
        messageData.put("time3", pushService.createDataItem("截至日期", "2023-06-30"));
        messageData.put("thing4", pushService.createDataItem("发布人员", "张三"));
        // 将订阅消息内容转换为JSON字符串
        String jsonData = messageData.toJSONString();
        pushService.sendSubscribeMessage(accessToken,openid,templateId,page,jsonData);
        return null;
    }
}
